import React, { useState, useEffect } from "react";
import {
  Button,
  Modal,
  Descriptions,
  PageHeader,
  Form,
  Input,
  message,
} from "antd";
import moment from "moment";
import "@wangeditor/editor/dist/css/style.css";
import { Editor, Toolbar } from "@wangeditor/editor-for-react";
import { IDomEditor, IEditorConfig } from "@wangeditor/editor";
import { AddArticle, ReadArticle, EditArticle } from "./request/api";
import { useNavigate, useParams } from "react-router-dom";

export default function Edit() {
  const date = new Date();

  const [editor, setEditor] = useState(null); // 存储 editor 实例
  const [html, setHtml] = useState("<p>hello</p>");
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [form] = Form.useForm();
  const [title, setTitle] = useState();
  const [subTitle, setSubTitle] = useState();
  const navigate = useNavigate();
  const params = useParams();

  const toolbarConfig = {};
  const editorConfig = {
    placeholder: "请输入内容...",
  };

  // 及时销毁 editor
  useEffect(() => {
    return () => {
      if (editor == null) return;
      editor.destroy();
      setEditor(null);
    };
  }, [editor]);

  useEffect(() => {
    if (params.id) {
      ReadArticle({ id: params.id }).then((res) => {
        if (res.errCode == 0) {
          setHtml(res.data.content);
          setTitle(res.data.title);
          setSubTitle(res.data.subTitle);
        }
      });
    }
  }, []);

  const showModal = () => {
    setIsModalVisible(true);
  };

  const handleOk = () => {
    form
      .validateFields()
      .then((values) => {
        form.resetFields();
        let { title, subTitle } = values;
        // console.log(html);
        if (params.id) {
          EditArticle({
            content: html,
            id: params.id,
            subTitle,
            title,
          }).then((res) => {
            if (res.errCode == 0) {
              message.success(res.message);
              navigate("/list");
            }
          });
        } else {
          AddArticle({
            title,
            subTitle,
            content: html,
          }).then((res) => {
            if (res.errCode == 0) {
              message.success(res.message);
              navigate("/list");
            } else {
              message.error(res.message);
            }
          });
        }
      })
      .catch((info) => {
        console.log("Validate Failed:", info);
      });
    setIsModalVisible(false);
  };

  const handleCancel = () => {
    setIsModalVisible(false);
  };

  return (
    <div>
      <PageHeader
        ghost={false}
        onBack={params.id ? () => window.history.back() : ""}
        title="文章编辑"
        subTitle={"当前日期" + "：" + moment(date).format("YYYY-MM-DD")}
        extra={[
          <Button key="1" type="primary" onClick={showModal}>
            提交文章
          </Button>,
        ]}
      ></PageHeader>
      <Modal
        title="填写文章标题"
        visible={isModalVisible}
        onOk={handleOk}
        onCancel={handleCancel}
        okText="提交"
        cancelText="取消"
      >
        <Form
          form={form}
          name="form_in_modal"
          initialValues={{ title, subTitle }}
          labelCol={{
            span: 3,
          }}
          wrapperCol={{
            span: 21,
          }}
          autoComplete="off"
        >
          <Form.Item
            label="标题"
            name="title"
            rules={[
              {
                required: true,
                message: "Please input your title!",
              },
            ]}
          >
            <Input />
          </Form.Item>

          <Form.Item label="副标题" name="subTitle">
            <Input />
          </Form.Item>
        </Form>
      </Modal>
      <div>
        <div
          style={{ border: "1px solid #ccc", zIndex: 100, marginTop: "15px" }}
        >
          <Toolbar
            editor={editor}
            defaultConfig={toolbarConfig}
            mode="default"
            // style={{ borderBottom: "1px solid #ccc" }}
          />
          <Editor
            defaultConfig={editorConfig}
            value={html}
            onCreated={setEditor}
            onChange={(editor) => setHtml(editor.getHtml())}
            mode="default"
            style={{ height: "200px" }}
          />
        </div>
      </div>
    </div>
  );
}
